eeccda59edaabb2ae5935a75c644d5f2f2cdda60
2 * JavaScript for Special:Upload
5 * @class mw.special.upload
9 var uploadWarning
, uploadLicense
,
10 ajaxUploadDestCheck
= mw
.config
.get( 'wgAjaxUploadDestCheck' ),
11 $license
= $( '#wpLicense' );
13 window
.wgUploadWarningObj
= uploadWarning
= {
14 responseCache
: { '': ' ' },
20 keypress: function () {
21 if ( !ajaxUploadDestCheck
) {
25 // Find file to upload
26 if ( !$( '#wpDestFile' ).length
|| !$( '#wpDestFile-warning' ).length
) {
30 this.nameToCheck
= $( '#wpDestFile' ).val();
33 if ( this.timeoutID
) {
34 clearTimeout( this.timeoutID
);
36 // Check response cache
37 if ( this.responseCache
.hasOwnProperty( this.nameToCheck
) ) {
38 this.setWarning( this.responseCache
[this.nameToCheck
] );
42 this.timeoutID
= setTimeout( function () {
43 uploadWarning
.timeout();
47 checkNow: function ( fname
) {
48 if ( !ajaxUploadDestCheck
) {
51 if ( this.timeoutID
) {
52 clearTimeout( this.timeoutID
);
54 this.nameToCheck
= fname
;
58 timeout: function () {
59 var $spinnerDestCheck
;
60 if ( !ajaxUploadDestCheck
|| this.nameToCheck
=== '' ) {
63 $spinnerDestCheck
= $.createSpinner().insertAfter( '#wpDestFile' );
65 ( new mw
.Api() ).get( {
67 titles
: ( new mw
.Title( this.nameToCheck
, mw
.config
.get( 'wgNamespaceIds' ).file
) ).getPrefixedText(),
69 iiprop
: 'uploadwarning',
71 } ).done( function ( result
) {
74 resultOut
= result
.query
.pages
[result
.query
.pageids
[0]].imageinfo
[0];
76 $spinnerDestCheck
.remove();
77 uploadWarning
.processResult( resultOut
, uploadWarning
.nameToCheck
);
81 processResult: function ( result
, fileName
) {
82 this.setWarning( result
.html
);
83 this.responseCache
[fileName
] = result
.html
;
86 setWarning: function ( warning
) {
87 $( '#wpDestFile-warning' ).html( warning
);
89 // Set a value in the form indicating that the warning is acknowledged and
90 // doesn't need to be redisplayed post-upload
92 $( '#wpDestFileWarningAck' ).val( '' );
94 $( '#wpDestFileWarningAck' ).val( '1' );
102 responseCache
: { '': '' },
104 fetchPreview: function ( license
) {
106 if ( !mw
.config
.get( 'wgAjaxLicensePreview' ) ) {
109 if ( this.responseCache
.hasOwnProperty( license
) ) {
110 this.showPreview( this.responseCache
[license
] );
114 $spinnerLicense
= $.createSpinner().insertAfter( '#wpLicense' );
116 ( new mw
.Api() ).get( {
118 text
: '{{' + license
+ '}}',
119 title
: $( '#wpDestFile' ).val() || 'File:Sample.jpg',
122 } ).done( function ( result
) {
123 $spinnerLicense
.remove();
124 uploadLicense
.processResult( result
, license
);
128 processResult: function ( result
, license
) {
129 this.responseCache
[license
] = result
.parse
.text
['*'];
130 this.showPreview( this.responseCache
[license
] );
133 showPreview: function ( preview
) {
134 $( '#mw-license-preview' ).html( preview
);
140 // AJAX wpDestFile warnings
141 if ( ajaxUploadDestCheck
) {
142 // Insert an event handler that fetches upload warnings when wpDestFile
144 $( '#wpDestFile' ).change( function () {
145 uploadWarning
.checkNow( $( this ).val() );
147 // Insert a row where the warnings will be displayed just below the
149 $( '#mw-htmlform-description tbody' ).append(
152 .attr( 'id', 'wpDestFile-warning' )
153 .attr( 'colspan', 2 )
158 if ( mw
.config
.get( 'wgAjaxLicensePreview' ) && $license
.length
) {
159 // License selector check
160 $license
.change( function () {
161 // We might show a preview
162 uploadLicense
.fetchPreview( $license
.val() );
165 // License selector table row
166 $license
.closest( 'tr' ).after(
169 $( '<td>' ).attr( 'id', 'mw-license-preview' )
174 // fillDestFile setup
175 $.each( mw
.config
.get( 'wgUploadSourceIds' ), function ( index
, sourceId
) {
176 $( '#' + sourceId
).change( function () {
177 var path
, slash
, backslash
, fname
;
178 if ( !mw
.config
.get( 'wgUploadAutoFill' ) ) {
181 // Remove any previously flagged errors
182 $( '#mw-upload-permitted' ).attr( 'class', '' );
183 $( '#mw-upload-prohibited' ).attr( 'class', '' );
185 path
= $( this ).val();
186 // Find trailing part
187 slash
= path
.lastIndexOf( '/' );
188 backslash
= path
.lastIndexOf( '\\' );
189 if ( slash
=== -1 && backslash
=== -1 ) {
191 } else if ( slash
> backslash
) {
192 fname
= path
.slice( slash
+ 1 );
194 fname
= path
.slice( backslash
+ 1 );
197 // Clear the filename if it does not have a valid extension.
198 // URLs are less likely to have a useful extension, so don't include them in the
201 mw
.config
.get( 'wgCheckFileExtensions' ) &&
202 mw
.config
.get( 'wgStrictFileExtensions' ) &&
203 mw
.config
.get( 'wgFileExtensions' ) &&
204 $( this ).attr( 'id' ) !== 'wpUploadFileURL'
207 fname
.lastIndexOf( '.' ) === -1 ||
209 fname
.slice( fname
.lastIndexOf( '.' ) + 1 ).toLowerCase(),
210 $.map( mw
.config
.get( 'wgFileExtensions' ), function ( element
) {
211 return element
.toLowerCase();
215 // Not a valid extension
216 // Clear the upload and set mw-upload-permitted to error
218 $( '#mw-upload-permitted' ).attr( 'class', 'error' );
219 $( '#mw-upload-prohibited' ).attr( 'class', 'error' );
220 // Clear wpDestFile as well
221 $( '#wpDestFile' ).val( '' );
227 // Replace spaces by underscores
228 fname
= fname
.replace( / /g
, '_' );
229 // Capitalise first letter if needed
230 if ( mw
.config
.get( 'wgCapitalizeUploads' ) ) {
231 fname
= fname
.charAt( 0 ).toUpperCase().concat( fname
.slice( 1 ) );
235 if ( $( '#wpDestFile' ).length
) {
236 // Call decodeURIComponent function to remove possible URL-encoded characters
237 // from the file name (bug 30390). Especially likely with upload-form-url.
238 // decodeURIComponent can throw an exception if input is invalid utf-8
240 $( '#wpDestFile' ).val( decodeURIComponent( fname
) );
242 $( '#wpDestFile' ).val( fname
);
244 uploadWarning
.checkNow( fname
);
250 // Add a preview to the upload form
253 * Is the FileAPI available with sufficient functionality?
255 function hasFileAPI() {
256 return window
.FileReader
!== undefined;
260 * Check if this is a recognizable image type...
261 * Also excludes files over 10M to avoid going insane on memory usage.
263 * TODO: Is there a way we can ask the browser what's supported in `<img>`s?
265 * TODO: Put SVG back after working around Firefox 7 bug <https://bugzilla.wikimedia.org/show_bug.cgi?id=31643>
270 function fileIsPreviewable( file
) {
271 var known
= ['image/png', 'image/gif', 'image/jpeg', 'image/svg+xml'],
272 tooHuge
= 10 * 1024 * 1024;
273 return ( $.inArray( file
.type
, known
) !== -1 ) && file
.size
> 0 && file
.size
< tooHuge
;
277 * Show a thumbnail preview of PNG, JPEG, GIF, and SVG files prior to upload
278 * in browsers supporting HTML5 FileAPI.
280 * As of this writing, known good:
283 * - Chrome 7.something
285 * TODO: Check file size limits and warn of likely failures
289 function showPreview( file
) {
294 thumb
= mw
.template
.get( 'mediawiki.special.upload', 'thumbnail.html' ).render();
296 thumb
.find( '.filename' ).text( file
.name
).end()
297 .find( '.fileinfo' ).text( prettySize( file
.size
) ).end();
299 $canvas
= $( '<canvas width="' + previewSize
+ '" height="' + previewSize
+ '" ></canvas>' );
300 ctx
= $canvas
[0].getContext( '2d' );
301 $( '#mw-htmlform-source' ).parent().prepend( thumb
);
303 fetchPreview( file
, function ( dataURL
) {
304 var img
= new Image(),
307 if ( meta
&& meta
.tiff
&& meta
.tiff
.Orientation
) {
308 rotation
= ( 360 - ( function () {
309 // See includes/media/Bitmap.php
310 switch ( meta
.tiff
.Orientation
.value
) {
323 img
.onload = function () {
324 var info
, width
, height
, x
, y
, dx
, dy
, logicalWidth
, logicalHeight
;
326 // Fit the image within the previewSizexpreviewSize box
327 if ( img
.width
> img
.height
) {
329 height
= img
.height
/ img
.width
* previewSize
;
331 height
= previewSize
;
332 width
= img
.width
/ img
.height
* previewSize
;
334 // Determine the offset required to center the image
335 dx
= ( 180 - width
) / 2;
336 dy
= ( 180 - height
) / 2;
337 switch ( rotation
) {
338 // If a rotation is applied, the direction of the axis
339 // changes as well. You can derive the values below by
340 // drawing on paper an axis system, rotate it and see
341 // where the positive axis direction is
345 logicalWidth
= img
.width
;
346 logicalHeight
= img
.height
;
351 y
= dy
- previewSize
;
352 logicalWidth
= img
.height
;
353 logicalHeight
= img
.width
;
356 x
= dx
- previewSize
;
357 y
= dy
- previewSize
;
358 logicalWidth
= img
.width
;
359 logicalHeight
= img
.height
;
362 x
= dx
- previewSize
;
364 logicalWidth
= img
.height
;
365 logicalHeight
= img
.width
;
369 ctx
.clearRect( 0, 0, 180, 180 );
370 ctx
.rotate( rotation
/ 180 * Math
.PI
);
371 ctx
.drawImage( img
, x
, y
, width
, height
);
372 thumb
.find( '.mw-small-spinner' ).replaceWith( $canvas
);
375 info
= mw
.msg( 'widthheight', logicalWidth
, logicalHeight
) +
376 ', ' + prettySize( file
.size
);
378 $( '#mw-upload-thumbnail .fileinfo' ).text( info
);
381 }, mw
.config
.get( 'wgFileCanRotate' ) ? function ( data
) {
383 meta
= mw
.libs
.jpegmeta( data
, file
.fileName
);
384 // jscs:disable requireCamelCaseOrUpperCaseIdentifiers, disallowDanglingUnderscores
385 meta
._binary_data
= null;
394 * Start loading a file into memory; when complete, pass it as a
395 * data URL to the callback function. If the callbackBinary is set it will
396 * first be read as binary and afterwards as data URL. Useful if you want
397 * to do preprocessing on the binary data first.
400 * @param {Function} callback
401 * @param {Function} callbackBinary
403 function fetchPreview( file
, callback
, callbackBinary
) {
404 var reader
= new FileReader();
405 if ( callbackBinary
&& 'readAsBinaryString' in reader
) {
406 // To fetch JPEG metadata we need a binary string; start there.
408 reader
.onload = function () {
409 callbackBinary( reader
.result
);
411 // Now run back through the regular code path.
412 fetchPreview( file
, callback
);
414 reader
.readAsBinaryString( file
);
415 } else if ( callbackBinary
&& 'readAsArrayBuffer' in reader
) {
416 // readAsArrayBuffer replaces readAsBinaryString
417 // However, our JPEG metadata library wants a string.
418 // So, this is going to be an ugly conversion.
419 reader
.onload = function () {
421 buffer
= new Uint8Array( reader
.result
),
423 for ( i
= 0; i
< buffer
.byteLength
; i
++ ) {
424 string
+= String
.fromCharCode( buffer
[i
] );
426 callbackBinary( string
);
428 // Now run back through the regular code path.
429 fetchPreview( file
, callback
);
431 reader
.readAsArrayBuffer( file
);
432 } else if ( 'URL' in window
&& 'createObjectURL' in window
.URL
) {
433 // Supported in Firefox 4.0 and above <https://developer.mozilla.org/en/DOM/window.URL.createObjectURL>
434 // WebKit has it in a namespace for now but that's ok. ;)
436 // Lifetime of this URL is until document close, which is fine
437 // for Special:Upload -- if this code gets used on longer-running
438 // pages, add a revokeObjectURL() when it's no longer needed.
440 // Prefer this over readAsDataURL for Firefox 7 due to bug reading
441 // some SVG files from data URIs <https://bugzilla.mozilla.org/show_bug.cgi?id=694165>
442 callback( window
.URL
.createObjectURL( file
) );
444 // This ends up decoding the file to base-64 and back again, which
445 // feels horribly inefficient.
446 reader
.onload = function () {
447 callback( reader
.result
);
449 reader
.readAsDataURL( file
);
454 * Format a file size attractively.
456 * TODO: Match numeric formatting
461 function prettySize( s
) {
462 var sizeMsgs
= ['size-bytes', 'size-kilobytes', 'size-megabytes', 'size-gigabytes'];
463 while ( s
>= 1024 && sizeMsgs
.length
> 1 ) {
465 sizeMsgs
= sizeMsgs
.slice( 1 );
467 return mw
.msg( sizeMsgs
[0], Math
.round( s
) );
471 * Clear the file upload preview area.
473 function clearPreview() {
474 $( '#mw-upload-thumbnail' ).remove();
478 * Check if the file does not exceed the maximum size
480 function checkMaxUploadSize( file
) {
483 function getMaxUploadSize( type
) {
484 var sizes
= mw
.config
.get( 'wgMaxUploadSize' );
486 if ( sizes
[type
] !== undefined ) {
492 $( '.mw-upload-source-error' ).remove();
494 maxSize
= getMaxUploadSize( 'file' );
495 if ( file
.size
> maxSize
) {
496 $error
= $( '<p class="error mw-upload-source-error" id="wpSourceTypeFile-error">' +
497 mw
.message( 'largefileserver', file
.size
, maxSize
).escaped() + '</p>' );
499 $( '#wpUploadFile' ).after( $error
);
508 if ( hasFileAPI() ) {
509 // Update thumbnail when the file selection control is updated.
510 $( '#wpUploadFile' ).change( function () {
512 if ( this.files
&& this.files
.length
) {
513 // Note: would need to be updated to handle multiple files.
514 var file
= this.files
[0];
516 if ( !checkMaxUploadSize( file
) ) {
520 if ( fileIsPreviewable( file
) ) {
528 // Disable all upload source fields except the selected one
530 var $rows
= $( '.mw-htmlform-field-UploadSourceField' );
532 $rows
.on( 'change', 'input[type="radio"]', function ( e
) {
533 var currentRow
= e
.delegateTarget
;
535 if ( !this.checked
) {
539 $( '.mw-upload-source-error' ).remove();
541 // Enable selected upload method
542 $( currentRow
).find( 'input' ).prop( 'disabled', false );
544 // Disable inputs of other upload methods
545 // (except for the radio button to re-enable it)
548 .find( 'input[type!="radio"]' )
549 .prop( 'disabled', true );
553 if ( !$( '#wpSourceTypeurl' ).prop( 'checked' ) ) {
554 $( '#wpUploadFileURL' ).prop( 'disabled', true );
559 // Prevent losing work
560 var allowCloseWindow
,
561 $uploadForm
= $( '#mw-upload-form' );
563 if ( !mw
.user
.options
.get( 'useeditwarning' ) ) {
564 // If the user doesn't want edit warnings, don't set things up.
568 $uploadForm
.data( 'origtext', $uploadForm
.serialize() );
570 allowCloseWindow
= mw
.confirmCloseWindow( {
572 return $( '#wpUploadFile' ).get( 0 ).files
.length
!== 0 ||
573 $uploadForm
.data( 'origtext' ) !== $uploadForm
.serialize();
576 message
: mw
.msg( 'editwarning-warning' ),
577 namespace: 'uploadwarning'
580 $uploadForm
.submit( function () {
584 }( mediaWiki
, jQuery
) );